package com.block.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.block.common.config.AliIPConfig;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.IPackageInfoService;
import com.block.common.service.LogFactory;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.ChannelInfo;
import com.block.db.entity.MemberInfo;
import com.block.db.mapper.MemberInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
public class MemberCommonServiceImpl implements IMemberCommonService {

    private static Logger log = LogFactory.getCommLog();

    @Autowired
    IPackageInfoService packageInfoService;
    @Resource
    MemberInfoMapper memberInfoMapper;
    @Autowired
    AliIPConfig aliIPConfig;

    @Override
    public MemberInfo saveRegisterMemberInfo(String clientType, String mobile, ChannelInfo reqChannelInfo,
                                             ApplicationInfo applicationInfo, String ip, Integer userType, String zhima){

        log.info("【用户信息注册】【clientType】{}【mobile】{}【channelCode】{}【ip】{}", clientType, mobile, reqChannelInfo.getChannelCode(), ip);

        return saveMemberInfo(mobile, reqChannelInfo, applicationInfo, userType, ip, zhima);

    }

    /**
     * 保存用户信息
     * @param mobile
     * @param reqChannelInfo
     * @param userType
     * @param ip
     * @return
     */
    @Override
    public MemberInfo saveMemberInfo(String mobile, ChannelInfo reqChannelInfo, ApplicationInfo appInfo, Integer userType, String ip, String zhima){

        /**
         * todo 新增用户信息异常报警
         *
         */

        try {

            MemberInfo memberInfo = new MemberInfo();
            memberInfo.setMobile(mobile);
            memberInfo.setMobileMd5(SecureUtil.md5(mobile).toLowerCase());
            memberInfo.setChannelCode(reqChannelInfo.getChannelCode());
            memberInfo.setChannelName(reqChannelInfo.getChannelName());

            memberInfo.setAppCode(appInfo.getAppCode());
            memberInfo.setAppName(appInfo.getAppName());
            memberInfo.setAppType(appInfo.getAppType());

            memberInfo.setDateInfo(LocalDate.now().toString());
            memberInfo.setReqIp(ip);
            memberInfo.setZhima(zhima);
            memberInfo.setLastLogintime(LocalDateTime.now());
            memberInfo.setType(ObjectUtil.isEmpty(userType)?0:userType);

            int insert = memberInfoMapper.insert(memberInfo);
            if (insert > 0){
                return memberInfo;
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return null;
    }

}
